package cn.edu.suda.schoolBus.util;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.edu.suda.schoolBus.bean.Driver;
import cn.edu.suda.schoolBus.bean.SchoolBus;
import cn.edu.suda.schoolBus.controller.DynamicCarNumberController;
import cn.edu.suda.schoolBus.service.CarNumberService;
import cn.edu.suda.schoolBus.service.DriverService;
import cn.edu.suda.schoolBus.service.DynamicCarNumberService;
import cn.edu.suda.schoolBus.service.SchoolBusService;

@Component
public class ScheduleUtil {

	private CarNumberService carNumberService;
	private DynamicCarNumberService dynamicCarNumberService;
	private static DriverService driverService;
	private static SchoolBusService schoolBusService;

	@Autowired
	public ScheduleUtil(CarNumberService carNumberService, DynamicCarNumberService dynamicCarNumberService,
			DriverService driverService, SchoolBusService schoolBusService) {
		this.carNumberService = carNumberService;
		this.dynamicCarNumberService = dynamicCarNumberService;
		ScheduleUtil.driverService = driverService;
		ScheduleUtil.schoolBusService = schoolBusService;
		dynamicCarNumberTask();
	}

	private void dynamicCarNumberTask() {
		new Timer().schedule(new TimerTask() {

			@Override
			public void run() {
				if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) == 0) {
					dynamicCarNumberService.destroyDynamicCarNumber();
					dynamicCarNumberService.addDynamicCarNumber(carNumberService.getCarNumber());
					DynamicCarNumberController.setI(0);
				}
			}
		}, new Date(), 60 * 60 * 1000);
	}

	public static void editDriver(int dId) {
		Driver driver = new Driver();
		driver.setdId(dId);
		driver.setdStatus(0);
		driverService.editDriver(driver);
		new Timer().schedule(new TimerTask() {

			@Override
			public void run() {
				driver.setdStatus(1);
				driverService.editDriver(driver);
			}
		}, 60 * 1000);
	}

	public static void editSchoolBus(int sbId) {
		SchoolBus schoolBus = new SchoolBus();
		schoolBus.setSbId(sbId);
		schoolBus.setSbStatus(0);
		schoolBusService.editSchoolBus(schoolBus);
		new Timer().schedule(new TimerTask() {

			@Override
			public void run() {
				schoolBus.setSbStatus(1);
				schoolBusService.editSchoolBus(schoolBus);
			}
		}, 60 * 1000);

	}

	public static List<String> getSchoolBusNumber() {
		return schoolBusService.getSchoolBusNumber();
	}
}
